package com.ptu.controller.user;

import com.ptu.constant.JwtClaimsConstant;
import com.ptu.dto.StoreDTO;
import com.ptu.dto.UsersDTO;
import com.ptu.dto.UsersDTO;
import com.ptu.dto.UsersLoginDTO;
import com.ptu.entity.Users;
import com.ptu.properties.JwtProperties;
import com.ptu.result.PageResult;
import com.ptu.result.Result;
import com.ptu.service.UsersService;
import com.ptu.utils.JwtUtil;
import com.ptu.vo.StoreVO;
import com.ptu.vo.UsersLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController("userUserController")
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "用户登录相关接口")
public class UsersController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param usersLoginDTO
     * @return
     */
    @PostMapping("/userlogin")
    @ApiOperation(value = "用户登录")
    public Result<UsersLoginVO> login(@RequestBody UsersLoginDTO usersLoginDTO) {
        log.info("用户登录：{}", usersLoginDTO);
        Users users = usersService.login(usersLoginDTO);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, users.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        UsersLoginVO usersLoginVO = UsersLoginVO.builder()
                .id(users.getId())
                .userName(users.getUsername())
                .name(users.getName())
                .token(token)
                .phone(users.getPhone())
                .sex(users.getSex())
                .idNumber(users.getIdNumber())
                .build();
        return Result.success(usersLoginVO);
    }

    /**
     * 用户注册
     * @param usersDTO
     * @return
     */
    @PostMapping
    @ApiOperation("用户注册")
    public Result save(@RequestBody UsersDTO usersDTO){
        log.info("用户注册：{}", usersDTO);
        System.out.println("当前线程id:" + Thread.currentThread().getId());
        usersService.save(usersDTO);
        return Result.success();
    }


    /**
     * 编辑员工信息
     * @param usersDTO
     * @return
     */
    @PutMapping
    @ApiOperation("用户编辑个人信息")
    public Result update(@RequestBody UsersDTO usersDTO){
        log.info("编辑用户信息：{}", usersDTO);
        usersService.update(usersDTO);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户")
    public Result<Users> getById(@PathVariable Long id){
        Users users = usersService.getById(id);
        return Result.success(users);
    }
}
